
package misc

import (
    "errors"
	"strings"
	"dhfshop/utils/helper"
	"strconv"
	"encoding/json"
	"dhfshop/models"
	//"dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)


//中国省市行政规划
type Area struct {
    //Id       int    `orm:"column(id);pk;auto" json:"id" form:"id"`             
	AreaId   int    `orm:"column(area_id);pk" json:"area_id" form:"area_id"`     /* 地区编号 */
    Area     string `orm:"column(area);size(128)" json:"area" form:"area"`       /* 地区名称 */
	ParentId int    `orm:"column(parent_id);index" json:"parent_id" form:"parent_id"`  /* 上级地区编号 */
}

func init() {
    orm.RegisterModel(new(Area))   
}

func AddArea(m *Area) (id int64, err error) {
	o := models.GetDefaultDB()
	v := &Area{AreaId: m.AreaId}
	if err = o.Read(v); err == orm.ErrNoRows {
		id, err = o.Insert(m)
	}
	return
}

func AddAreas(list []*Area) (err error) {
	size := len(list)
	o := models.GetDefaultDB()
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}
	return
}

func InitDefaultAreas(areaJson string) (err error) {
	u := map[string]string{}
	err = json.Unmarshal([]byte(areaJson), &u)
    if err != nil {
        return err        
    }
	srcDataCount := int64(len(u)) 
	dstDataCount, _:= GetAreasCount()
	if srcDataCount == dstDataCount {
	    return nil
	}
	areas := []*Area{}
	for key, value := range u {
	    area := new(Area)
		area.AreaId, _= strconv.Atoi(key)
		area.Area = value
		if area.ParentId, err = getParentId(key); err == nil {
		   areas = append(areas, area)
		}
    }
	if len(areas) > 0 {
	    AddAreas(areas)
	}
	return nil
}

func getParentId(areaCode string) (parentCode int, err error) {
	subCode := helper.Substr(areaCode,2,4)
	if subCode == "0000" {
	   parentCode = 0
	   return parentCode, nil
	}
	subCode = helper.Substr(areaCode,4,2)
	if subCode == "00" {
	   prefixCode := helper.Substr(areaCode,0,2)
	   prefixCode = prefixCode + "0000"
	   parentCode, err = strconv.Atoi(prefixCode)
	   if err != nil{
	       return parentCode, err
	   }
	   return parentCode, nil
	}
	prefixCode := helper.Substr(areaCode,0,4)
	prefixCode = prefixCode + "00"
	parentCode, err = strconv.Atoi(prefixCode)
	if err != nil{
	    return parentCode, err
	}
	return parentCode, nil
}

func GetAreaByAreaId(id int) (v *Area, err error) {
	o := models.GetDefaultDB()
	v = &Area{AreaId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// 根据区名获取区域
func GetAreaByArea(name string) ([]*Area, error) {
	var areas []*Area
	o := models.GetDefaultDB()
	sql := "select * from area_value where name LIKE '%?%'"
	_, err := o.Raw(sql, name).QueryRows(&areas)
	if err != nil {
		return []*Area{}, err
	}
	return areas, nil
}


func GetAllAreas(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*Area,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Area))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Area
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetAreasCount()(int64, error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Area))
	cnt, err := qs.Count()
	return cnt, err
}
